import Vue from 'vue'
import store from '../index'
import { asyncRouterMap, constantRouterMap } from '@/router'
import _ from 'underscore'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(modules, route) {
  console.log(modules.split(","),route.name)

  return _.indexOf(modules.split(","), route.name)>=0
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param modules
 */
function filterAsyncRouter(asyncRouterMap, modules) {

  asyncRouterMap.forEach(function (item) {
    if(item.children&&item.children.length>0){ //如果有子节点
      var newChildren= []
      item.children.forEach(function (child) {
        if(child.flex){ //存在
          if(modules.indexOf(child.name)>=0){
            newChildren.push(child)
          }
        }else{
          newChildren.push(child)
        }

      })
      item.children=newChildren
    }
  })
  var newMap=[]
  asyncRouterMap.forEach(function (item) {
    if(item.children&&item.children.length>0){ //如果有子节点
      newMap.push(item)
    }
  })
  return newMap
}

const permission = {
  state: {
    routers: constantRouterMap,
    addedRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addedRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        let { modules } = data
        console.log("modules:",modules)
        if(modules.indexOf("interview")!=-1){
          modules += ',interviewSet,jobInterview'
        }
		  if(modules.indexOf("train")!=-1){
			  modules += ',jobTrain'
		  }
        let accessedRouters
        let modules_list =  modules.split(",");
        if (_.indexOf(modules_list,'super') >= 0) {
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterMap, modules)
          // accessedRouters = asyncRouterMap
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
